package ro.dandanciu.webgallery.util.email;

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

public class EmailSender {

    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(EmailSender.class);

    private static final String SMTP_HOST_NAME = "smtp.gmail.com";

    private static final String SMTP_PORT = "465";

    private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

    private static String MY_ADDRESS = "web.gallery.app@gmail.com";

    private static final String MY_PASSWORD = "web.gallery.app.password";


    public static void send(final EmailMessage message) {
        if (logger.isDebugEnabled()) {
            logger.debug("send(EmailMessage) - start");
        }

        try {

            final Properties props = System.getProperties();

            props.put("mail.smtp.host", SMTP_HOST_NAME);
            props.put("mail.smtp.auth", "true");
            props.put("mail.debug", "true");
            props.put("mail.smtp.port", SMTP_PORT);
            props.put("mail.smtp.socketFactory.port", SMTP_PORT);
            props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.put("mail.smtp.socketFactory.fallback", "false");

            final Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {

                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(MY_ADDRESS, MY_PASSWORD);
                }
            });

            final Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(MY_ADDRESS));

            final InternetAddress[] addressTo = new InternetAddress[message
                    .getToAddresses().size()];
            int i = 0;
            for (final String to : message.getToAddresses()) {
                addressTo[i++] = new InternetAddress(to);
            }

            msg.setRecipients(Message.RecipientType.TO, addressTo);
            msg.setSubject(message.getSubject());
            msg.setText(message.getBody());
            msg.setContent(message.getBody(), "text/html");
            msg.setSentDate(new Date());



            Transport.send(msg);

            if (logger.isDebugEnabled()) {
                logger.debug("Email: " + message + " sent.");
            }
        } catch (final Exception ex) {
            logger.error("send(EmailMessage)", ex);
        }

        if (logger.isDebugEnabled()) {
            logger.debug("send(EmailMessage) - end");
        }
    }


}
